import 'dart:async';

class EventBus {
  factory EventBus() => _getInstance();

  static EventBus _instance;

  static EventBus _getInstance() {
    if (_instance == null) {
      _instance = EventBus._internal();
    }
    return _instance;
  }

  EventBus._internal() {
    _streamController = StreamController.broadcast();
  }

  StreamController _streamController;

  StreamController get streamController => _streamController;

  ///订阅
  Stream<T> on<T>() {
    if (T == dynamic) {
      return streamController.stream;
    } else {
      return streamController.stream.where((event) => event is T).cast<T>();
    }
  }

  ///发射
  void fire(event) {
    streamController.add(event);
  }

  ///发射指定
  void post(EventMessage eventMessage) {
    fire(eventMessage);
  }

  ///订阅指定
  Stream<EventMessage> onEvent() {
    return streamController.stream.where((event) => event is EventMessage).cast<EventMessage>();
  }

  void destroy() {
    _streamController.close();
  }
}

///eventbus消息传递类
class EventMessage {
  ///区分不同EventMessage的标记
  String tag;
  String str1;
  String str2;
  int int1 = 0;
  int int2 = 0;
  double double1 = 0;
  double double2 = 0;
  Object obj1;
  Object obj2;
  Map<String, dynamic> map;

  EventMessage(this.tag, {this.str1, this.str2, this.int1, this.int2, this.double1, this.double2, this.obj1, this.obj2, this.map});
}
